import FamilySaveOrUpdateModal, {
  FamilyCreateOrUpdateInfo,
} from '@/pages/family-counselor/family-newOrUpdate-modal';
import {deleteFamily, deleteUser, FamilyInfo, FamilyListReqParam, getFamilyList} from '@/services/family/api';
import { PlusOutlined } from '@ant-design/icons';
import { ActionType, PageContainer, ProColumnType, ProTable } from '@ant-design/pro-components';
import {Button, message, Modal} from 'antd';
import to from 'await-to-js';
import React, { useRef, useState } from 'react';

const FamilyList: React.FC = () => {
  const [currentModalFamilyInfo, setCurrentModalFamilyInfo] = useState<FamilyCreateOrUpdateInfo>(
    {},
  );
  const [familySaveOrUpdateModalVisible, setFamilySaveOrUpdateModalVisible] =
    useState<boolean>(false);

  const params = {
    current: 1,
    pageSize: 50,
  };

  const proTableRef = useRef<ActionType>();
  const showFamilyInfoModal = (familyInfo: FamilyCreateOrUpdateInfo) => {
    setCurrentModalFamilyInfo(familyInfo);
    setFamilySaveOrUpdateModalVisible(true);
  };

  const handleDeleteFamily = async (familyId: number) => {
    const [err,res] = await to(deleteFamily(familyId));
    if(err || !res?.result) {
      return message.error("家庭删除失败: " + err?.message);
    }
    proTableRef?.current?.reload();
    return message.success(`家庭删除成功`);
  }

  const columns: ProColumnType<FamilyInfo>[] = [
    {
      title: '家庭ID',
      dataIndex: 'id',
      key: 'id',
      hideInSearch: true,
    },
    {
      title: '家庭名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '家庭码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '创建日期',
      dataIndex: 'createTime',
      key: 'createTime',
      valueType: 'dateRange',
      render(_text, record) {
        return record.createTime;
      },
    },
    {
      hideInSearch: true,
      title: '操作',
      dataIndex: 'lastReportTime',
      key: 'id',
      render(_text, record): React.JSX.Element {
        return (
          <>
            <Button
              size="small"
              type="primary"
              onClick={() => {
                showFamilyInfoModal({
                  id: record.id,
                  name: record.name,
                  code: record.code,
                });
              }}
            >
              编辑家庭
            </Button>
            &nbsp;
            <Button
              size="small"
              variant="solid"
              color="danger"
              onClick={() => {
                Modal.confirm({
                  title: `删除家庭${record.name}的操作是不可逆的，确认执行吗？`,
                  okText: '确定',
                  cancelText: '取消',
                  onOk() {
                    handleDeleteFamily(record.id)
                  },
                })
              }}
            >
              删除家庭
            </Button>
          </>
        );
      },
    },
  ];

  return (
    <PageContainer
      header={{
        title: null,
      }}
    >
      <ProTable
        defaultSize="small"
        actionRef={proTableRef}
        rowKey={'id'}
        columns={columns}
        // params 是需要自带的参数
        // 这个参数优先级更高，会覆盖查询表单的参数
        params={params}
        // 第一个参数 params 查询表单和 params 参数的结合
        // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
        request={async (params: FamilyListReqParam) => {
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改
          if(params.createTime) {
            params.createStartDate = params.createTime[0] + ' 00:00:00';
            params.createEndDate = params.createTime[1] + ' 23:59:59';
          }
          const [err, baseResponse] = await to(getFamilyList(params));
          if (err) {
            return { data: [], success: false };
          }
          const familyList = baseResponse?.result;

          // 按照创建时间倒序排列
          familyList.sort((a, b) => {
            return new Date(b.createTime).getTime() - new Date(a.createTime).getTime();
          });
          return {
            data: familyList,
            success: baseResponse?.code === '0'
          };
        }}
        search={{
          searchText: '搜索',
          labelWidth: 'auto',
          collapsed: false,
          span: 6,
        }}
        debounceTime={100}
        toolBarRender={() => [
          <Button
            size="small"
            key="3"
            type="primary"
            onClick={() => {
              showFamilyInfoModal({});
            }}
          >
            <PlusOutlined />
            新建家庭
          </Button>,
        ]}
      />

      <FamilySaveOrUpdateModal
        onOpenChange={setFamilySaveOrUpdateModalVisible}
        familyInfo={currentModalFamilyInfo}
        modalVisible={familySaveOrUpdateModalVisible}
        onSubmit={(familyInfo: FamilyCreateOrUpdateInfo) => {
          console.log(familyInfo);
          // @ts-ignore 刷新家庭列表
          proTableRef?.current?.reloadAndRest();
        }}
      />
    </PageContainer>
  );
};

export default FamilyList;
